package cn.edu.seu.ssny.controller.web;

import cn.edu.seu.ssny.common.JsonResult;
import cn.edu.seu.ssny.controller.BaseController;
import cn.edu.seu.ssny.entity.*;
import cn.edu.seu.ssny.service.*;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/web/modifydata")
public class ModifyDataController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(ModifyDataController.class);


    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IDeviceDataService deviceDataService;


    @RequestMapping(value = { "/index"})
    public String index(HttpSession session) {
        return "web/data/modifydata";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap map, HttpSession session) {
        List<Device> deviceList = deviceService.findByEnterprise((Enterprise) session.getAttribute("enterprise"));
        map.put("deviceList", deviceList);
        return "web/data/modifyform";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable Integer id, ModelMap map, HttpSession session) {
        DeviceData deviceData = deviceDataService.find(id);
        List<Device> deviceList = deviceService.findByEnterprise((Enterprise) session.getAttribute("enterprise"));
        map.put("deviceData", deviceData);
        map.put("deviceList", deviceList);
        return "web/data/modifyform";
    }

    @RequestMapping(value= {"/edit"} ,method = RequestMethod.POST)
    @ResponseBody
    public JsonResult address(DeviceData deviceData, ModelMap map, HttpSession session){
        String device_id = request.getParameter("device_id");
        Device device = null;
        if(!device_id.equals(""))
            device = deviceService.find(Integer.parseInt(device_id));
        try {
            deviceDataService.saveOrModify(deviceData, device);

        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }
}
